﻿using System;
namespace Netbits.TelnetServer.Parameters
{
	public class ParameterString : ParameterBase
	{
		#region Private Variables

		string _Value;
		string _DefaultValue;
		int _MinLength = 0;
		int _MaxLength = int.MaxValue;

		#endregion

		#region Constructor

		public ParameterString( string Name_ )
			: base( Name_, "STRING" )
		{
		}

		#endregion

		#region Public Properties

		public int MinLength
		{
			get
			{
				using( _Lock.Read() )
					return _MinLength;
			}
			set
			{
				using( _Lock.Write() )
					_MinLength = value;
			}
		}

		public int MaxLength
		{
			get
			{
				using( _Lock.Read() )
					return _MaxLength;
			}
			set
			{
				using( _Lock.Write() )
					_MaxLength = value;
			}
		}

		public string Value
		{
			get
			{
				if( _HasValue )
					return _Value;
				if( _HasDefaultValue )
					return _DefaultValue;

				throw new InvalidOperationException( "value not set" );
			}
		}

		public string DefaultValue
		{
			get
			{
				using( _Lock.Read() )
					return _DefaultValue;
			}
			set
			{
				using( _Lock.Write() )
				{
					_DefaultValue = value;
					_HasDefaultValue = true;
				}
			}
		}

		#endregion

		#region Overrides

		internal override void CopyFrom( ParameterBase Parameter_ )
		{
			ParameterString ps = Parameter_ as ParameterString;
			if( ps == null )
				throw new ArgumentException( "Parameter_ is not a type of ParameterString" );

			_Value = ps._Value;
			_DefaultValue = ps._DefaultValue;
			_MinLength = ps._MinLength;
			_MaxLength = ps._MaxLength;

			base.CopyFrom( Parameter_ );
		}

		internal override void ResetValues()
		{
			_Value = string.Empty;
			base.ResetValues();
		}

		internal override void SetValue( string Value_ )
		{
			if( Value_.Length < _MinLength || Value_.Length > _MaxLength )
				throw new Exception( string.Format( "invalid value '{0}' for parameter '{1}'. value-length '{2}' is out of range <{3} and >{4}", Value_, _Name, Value_.Length, _MinLength, _MaxLength ) );

			_Value = Value_;
			base.SetValue( Value_ );
		}

		internal override void PrintInfo( NetbitsTelnetClientSession Session_, string Search_ )
		{
			string snd = string.Empty;
			if( !string.IsNullOrEmpty( Description ) )
				snd = Description + Environment.NewLine;

			snd += "this parameter need an string value!";
			Session_.Send( snd );
		}

		#endregion
	}
}
